import { Middleware } from 'koa';

const logHandle: Middleware = async (ctx, next) => {
  const timer = Date.now();

  if (ctx.method === 'OPTIONS') {
    ctx.body = {};
  } else {
    console.info(`===>[${ctx.method + ' '.repeat(5 - ctx.method.length)}]`, ctx.url);
    await next();
    console.info(`<===[${ctx.response.status}: ${Date.now() - timer}ms]`);
  }

  ctx.set({
    'Access-Control-Allow-Origin': ctx.headers.origin || '',
    'Access-Control-Allow-Methods': 'POST,OPTIONS,GET',
    'Access-Control-Allow-Credentials': 'true',
    'Access-Control-Allow-Headers': 'accept,x-requested-with,Content-Type',
  });
};
export default logHandle;
